package com.xuhj.mysmsmanager;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.SmsManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.xuhj.mysmsmanager.service.ListenerSMSService;
import com.xuhj.mysmsmanager.service.MyServiceConnection;
import com.xuhj.mysmsmanager.utils.OkHttpUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private LinearLayout ll;
    private LinearLayout ll_oval;
    private ImageView image;
    private TextView button;
    private boolean isStart = false;
    private static final String GET_SIMS_URL = "https://newvts.hzbdtech.com/pingtai/remote-sims/remote-query";
    private static final String GET_SIMS_TEMPLATE_URL = "https://newvts.hzbdtech.com/pingtai/remote-params-sms/remote-query";
    public static final String REPORT_SUCCESS_URL = "https://newvts.hzbdtech.com/pingtai/remote-sims/send-success/";
    public static List<String> templateList;
    private JSONArray jsonArray = new JSONArray();
    private boolean templateRequestFlag = false;
    private boolean simRequestFlag = false;
    private Runnable runnable;

    public void onBindService() {
        MyServiceConnection connection = new MyServiceConnection();
        Intent intent = new Intent(this, ListenerSMSService.class);
        bindService(intent, connection, BIND_AUTO_CREATE);
    }

    private List<String> getSimTemplates() {
        Request request = new Request.Builder().url(GET_SIMS_TEMPLATE_URL).build();
        OkHttpUtil.getHttpClient(60).newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                templateRequestFlag = true;
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                assert response.body() != null;
                String result = response.body().string();
                if (result.length() > 0) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        JSONArray data = jsonObject.getJSONArray("data");
                        if (data.length() > 0) {
                            List<String> list = new ArrayList<>(data.length());
                            for (int i=0; i<data.length(); i++) {
                                list.add(data.getJSONObject(i).getString("smsValue"));
                            }
                            templateList = list;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                templateRequestFlag = true;
            }
        });
        while (!templateRequestFlag){
            System.out.println("等待请求模板返回");
        }
        return templateList;
    }

    private JSONArray getDataByNet() {
        Request request = new Request.Builder().url(GET_SIMS_URL).build();
        OkHttpUtil.getHttpClient(60).newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                simRequestFlag = true;
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                assert response.body() != null;
                String result = response.body().string();
                List<String> simTemplates = getSimTemplates();
                if (result.length() > 0 && simTemplates != null && simTemplates.size() > 0) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        Object dataObj = jsonObject.get("data");
                        if (!dataObj.toString().equals("null")) {
                            JSONArray data = jsonObject.getJSONArray("data");
                            if (data.length() > 0) {
                                for (int i = 0; i < data.length(); i++) {
                                    JSONObject json = data.getJSONObject(i);
                                    try {
                                        json.put("phone", json.get("sim"));
                                        json.put("msg", new JSONArray(simTemplates));
                                        jsonArray.put(json);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                simRequestFlag = true;
            }
        });
        while (!simRequestFlag){
            System.out.println("等待请求sim信息返回");
        }
        return jsonArray;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onBindService();
        ImmersionBar.with(this).statusBarDarkFont(true).init();
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.button);
        ll = findViewById(R.id.ll);
        ll_oval = findViewById(R.id.ll_oval);
        image = findViewById(R.id.image);
        ll_oval.setOnClickListener(view -> {
            if (isStart) {
                //关闭
                isStart = false;
                setView(false);
                finish();
            } else {
                //开启
                isStart = true;
                setView(true);
                String[] p = {Permission.READ_PHONE_STATE, Permission.SEND_SMS, Permission.RECEIVE_MMS, Permission.READ_SMS, Permission.RECEIVE_MMS};
                boolean isOk = XXPermissions.isGranted(MainActivity.this, p);
                Handler handler = new Handler();
                runnable = () -> {
                    jsonArray = new JSONArray();
//                    jsonArray = getDataByNet();
                    JSONObject json = new JSONObject();
                    try {
                        json.put("phone", "15158125032");
                        List<String> list = new ArrayList<>(1);
                        list.add("#000000,STIP:123.56.239.182,20048");
                        json.put("msg", new JSONArray(list));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    jsonArray.put(json);
                    if (jsonArray != null && jsonArray.length() > 0) {
                        for (int i = 0; i < jsonArray.length(); i++) {
                            try {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
                                sendOne(jsonObject.getString("phone"), jsonObject.getJSONArray("msg"));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
//                Toast.makeText(MainActivity.this, "接口数据为空", Toast.LENGTH_SHORT);
                        Log.e("wait log", "wait");
                    }
                    handler.postDelayed(runnable, 1800000);
                };
                if (isOk) {
                    sendAll(runnable, handler);
                } else {
                    setPermissions(runnable, handler);
                }
            }
        });
    }

    private void setView(boolean isStart) {
        if (isStart) {
            templateRequestFlag = false;
            simRequestFlag = false;
            button.setText("暂停服务");
            image.setImageResource(R.mipmap.stop);
            ll_oval.setBackgroundResource(R.drawable.button_shape2);
        } else {
            button.setText("启动服务");
            image.setImageResource(R.mipmap.open);
            ll_oval.setBackgroundResource(R.drawable.button_shape);
        }
    }

    private void setPermissions(Runnable runnable, Handler handler) {
        XXPermissions.with(this)
                // 申请单个权限
                .permission(Permission.READ_PHONE_STATE)
                .permission(Permission.SEND_SMS)
                .permission(Permission.RECEIVE_MMS)
                .permission(Permission.READ_SMS)
                .permission(Permission.RECEIVE_MMS)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            Toast.makeText(MainActivity.this, "获取短信权限成功", Toast.LENGTH_SHORT).show();
                            sendAll(runnable, handler);
                        } else {
                            Toast.makeText(MainActivity.this, "获取部分权限成功，但部分权限未正常授予", Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            Toast.makeText(MainActivity.this, "被永久拒绝授权，请手动授予短信权限", Toast.LENGTH_LONG).show();
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(MainActivity.this, permissions);
                        } else {
                            Toast.makeText(MainActivity.this, "获取录音和日历权限失败", Toast.LENGTH_LONG).show();
                        }
                    }
                });
    }

    private void sendAll(Runnable runnable, Handler handler) {
        ll.removeAllViews();
        button.setText("关闭服务");
        handler.postDelayed(runnable, 1);
    }

    private String SMS_SEND_ACTIOIN = "SMS_SEND";
    private String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";

    private void sendOne(String number, JSONArray contents) {
        try {
            for (int i=0; i<contents.length(); i++) {
                String content = contents.getString(i);
                SmsManager sManager = SmsManager.getDefault();//获取SmsManager 实例
                Intent itSend = new Intent(SMS_SEND_ACTIOIN);//设置intent
                Bundle bundle = new Bundle();
                bundle.putString("number", number);//将当前的号码设置进去，在广播接收可以获取到
                bundle.putString("content", content);
                itSend.putExtras(bundle);

                PendingIntent mSendPI = PendingIntent.getBroadcast(MainActivity.this, (int) System.currentTimeMillis(), itSend, PendingIntent.FLAG_CANCEL_CURRENT);//根据intent获取PendingIntent实例
                registerReceiver(new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context _context, Intent _intent) {
                        Bundle bundle = _intent.getExtras();
                        String number = bundle.getString("number");
                        String content = bundle.getString("content");
                        switch (getResultCode()) {
                            case Activity.RESULT_OK:
                                String msg = "正在发送短信:\n " + content + "到" + number;
                                setTextView(msg, number);
                                break;
                            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:    //普通错误
                                setTextView("普通错误！" + "号码:" + number + " 内容:" + content, number);
                                break;
                            case SmsManager.RESULT_ERROR_RADIO_OFF:         //无线广播被明确地关闭
                                setTextView("无线广播被明确地关闭!" + "号码:" + number + " 内容:" + content, number);
                                break;
                            case SmsManager.RESULT_ERROR_NULL_PDU:          //没有提供pdu
                                setTextView("没有提供pdu!" + "号码:" + number + " 内容:" + content, number);
                                break;
                            case SmsManager.RESULT_ERROR_NO_SERVICE:         //服务当前不可用
                                setTextView("服务当前不可用!" + "号码:" + number + " 内容:" + content, number);
                                break;
                        }

                    }
                }, new IntentFilter(SMS_SEND_ACTIOIN));

                //创建接收返回的接收状态的Intent
                Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);

                deliverIntent.putExtras(bundle);
                PendingIntent deliverPI = PendingIntent.getBroadcast(this, (int) System.currentTimeMillis(), deliverIntent, PendingIntent.FLAG_CANCEL_CURRENT);
                registerReceiver(new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context _context, Intent _intent) {
                        Bundle bundle = _intent.getExtras();
                        String number = bundle.getString("number");
                        String content = bundle.getString("content");
                        setTextViewFollowTag("已接收到短信: " + number + "接收" + content, number);
                    }

                }, new IntentFilter(DELIVERED_SMS_ACTION));


                if (content.length() > 70) {//短信内容大于70字数
                    ArrayList<String> divideContents = sManager.divideMessage(content);//将短信切分成集合
                    ArrayList<PendingIntent> mSendPIs = new ArrayList<>();
                    ArrayList<PendingIntent> deliverPIs = new ArrayList<>();
                    for (String text : divideContents) {
                        mSendPIs.add(PendingIntent.getBroadcast(MainActivity.this, (int) System.currentTimeMillis(), itSend, PendingIntent.FLAG_UPDATE_CURRENT));
                        deliverPIs.add(PendingIntent.getBroadcast(this, (int) System.currentTimeMillis(), deliverIntent, PendingIntent.FLAG_CANCEL_CURRENT));
                    }
                    sManager.sendMultipartTextMessage(number, null, divideContents, mSendPIs, deliverPIs);//调用这个方法后发短信看似只发一条，但实际上是帮我们发了很多条，收费也是按多条收费
                } else {//短信内容小于70字数则直接发送
                    sManager.sendTextMessage(number, null, content, mSendPI, deliverPI);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setTextView(String msg, String number) {
        boolean isExistence = false;
        for (int i = 0; i < ll.getChildCount(); i++) {
            TextView textView1 = (TextView) ll.getChildAt(i);
            String text = textView1.getText().toString();
            if (text.equals(msg)) {
                isExistence = true;
            }
        }
        if (!isExistence) {
            TextView textView = new TextView(MainActivity.this);
            textView.setTextColor(Color.BLACK);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.topMargin = 20;
            params.bottomMargin = 20;
            params.leftMargin = 20;
            params.rightMargin = 20;
            textView.setLayoutParams(params);
            textView.setText(msg);
            textView.setTag(number);
            ll.addView(textView);
        }
    }

    private void setTextViewFollowTag(String msg, String number) {
        boolean isExistence = false;
        for (int i = 0; i < ll.getChildCount(); i++) {
            TextView textView1 = (TextView) ll.getChildAt(i);
            String text = textView1.getText().toString();
            if (text.equals(msg)) {
                isExistence = true;
            }
        }
        if (!isExistence) {
            TextView textView = new TextView(MainActivity.this);
            textView.setTextColor(Color.BLACK);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.topMargin = 20;
            params.bottomMargin = 20;
            params.leftMargin = 20;
            params.rightMargin = 20;
            textView.setLayoutParams(params);
            textView.setText(msg);
            int index = 0;
            for (int i = 0; i < ll.getChildCount(); i++) {
                TextView textView1 = (TextView) ll.getChildAt(i);
                String tag = (String) textView1.getTag();
                if (!TextUtils.isEmpty(tag)) {
                    if (number.equals(tag)) {
                        index = i + 1;
                        break;
                    }
                }

            }
            if (index != 0) {
                ll.addView(textView, index);
            } else {
                ll.addView(textView);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == XXPermissions.REQUEST_CODE) {
            if (XXPermissions.isGranted(this, Permission.READ_PHONE_STATE) &&
                    XXPermissions.isGranted(this, Permission.SEND_SMS)
                    &&
                    XXPermissions.isGranted(this, Permission.RECEIVE_MMS)
                    &&
                    XXPermissions.isGranted(this, Permission.READ_SMS)) {
                Toast.makeText(MainActivity.this, "用户已经在权限设置页授予了短信权限", Toast.LENGTH_LONG);
            } else {
                Toast.makeText(MainActivity.this, "用户没有在权限设置页授予权限", Toast.LENGTH_LONG);
            }
        }
    }
}